package network_programming.np1_socket_and_serversocket;

import java.net.*;

public class Demo {
    public static void main(String[] args){
        Demo demo = new Demo();
        try {
            demo.test_01();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        demo.test_02();
        demo.test_03();
    }

    public void test_01() throws UnknownHostException {
        InetAddress address = InetAddress.getByName("www.csdn.net");    // 根据主机名获取其网络地址
        String name = address.getHostName();    // 获取主机名
        String ip = address.getHostAddress();   // 获取ip地址
        System.out.println(name + ": " + ip);
    }
    public void test_02() {
        InetSocketAddress socketAddress1 = new InetSocketAddress("127.0.0.1", 9090); //根据ip地址和端口号创建套接字地址
        InetSocketAddress socketAddress2 = new InetSocketAddress("www.csdn.net", 9091); //根据主机名和端口号创建套接字地址
        InetSocketAddress socketAddress3 = new InetSocketAddress(9092); //根据端口号创建套接字地址，ip地址为0.0.0.0（任意地址）
        System.out.println(socketAddress1.getHostName() + ": " + socketAddress1.getAddress() + ":" + socketAddress1.getPort());
        System.out.println(socketAddress2.getHostName() + ": " + socketAddress2.getAddress()+ ":" + socketAddress2.getPort());
        System.out.println(socketAddress3.getHostName() + ": " + socketAddress3.getAddress()+ ":" + socketAddress3.getPort());
    }
    public void test_03() {
        System.out.println();
        try {
            URL url = new URL("http://www.baidu.com:80/index.html?uname=dream&age=18#a");
            System.out.println("协议：" + url.getProtocol());
            System.out.println("域名|ip：" + url.getHost());
            System.out.println("端口：" + url.getPort());
            System.out.println("资源路径：" + url.getPath());
            System.out.println("请求资源文件名：" + url.getFile());
            System.out.println("请求参数：" + url.getQuery());
            System.out.println("锚点：" + url.getRef());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
